/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dusin.task;

import com.tlf.dyjc5.service.M5Service;
import com.tlf.dyjc5.service.RsjService;
import com.tlf.dyjc5.service.TaskService;
import com.tlf.dyjc5.service.TaskUploadService;
import com.tlf.dyjc5.service.Temp5MService;
import com.tlf.dyjc5.service.YsjService;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.dusin.commonutil.DateUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author tengyu
 */
public class AutoTaskThread extends Thread {

    boolean stop = false;
    private ServletContext servletContext;
    //static Logger logger = Logger.getLogger(AutoTaskThread.class);

    public AutoTaskThread(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void makeItStop() {
        stop = true;
    }

    @Override
    public void run() {
        int rsjFlag = 0;    //标记日数据是否处理过，0表示初始状态。rsjFlag==12,表示12日数据已处理过
        int ysjFlag = 0;    //标记月数据是否处理过，0表示初始状态，ysjFlag==12，表示12月日数据以处理过
        int data5mFlag = 0; //标记5分钟数据是否处理过，0表示初始状态。data5mFlag = 3,表示前3日的数据已经处理过
        
        int rsjRecallFlag = 0;    //标记日数据是否补招过，0表示初始状态。同上。
        int ysjRecallFlag = 0;    //标记月数据是否补招过，0表示初始状态，同上。

        int rsjUploadFlag = 0;
        int ysjUploadFlag = 0;

        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        RsjService rsjService = (RsjService) context.getBean("rsjServiceProxy");
        YsjService ysjService = (YsjService) context.getBean("ysjServiceProxy");
        TaskService taskService = (TaskService) context.getBean("taskService");
        TaskUploadService taskUploadService = (TaskUploadService) context.getBean("taskUploadService");
        Temp5MService temp5MService = (Temp5MService)context.getBean("temp5mServiceProxy");
        M5Service m5Service  = (M5Service)context.getBean("m5Service");
        String currentOrgCode = (String) this.servletContext.getAttribute("currentOrgCode");
        String rsjRateBase = (String) this.servletContext.getAttribute("rsjRateBase");
        String ysjRateBase = (String) this.servletContext.getAttribute("ysjRateBase");
        String rsjAutoTime = (String) this.servletContext.getAttribute("rsjAutoProcessTime");
        String isRsjAdjust = (String) this.servletContext.getAttribute("isRsjAdjust");
        String data5mAutoGenTime =(String)this.servletContext.getAttribute("data5mAutoGenTime");
        
        int startDay = 20;
        int rsjHour = 4;
        int rsjMin = 30;
        boolean rsjSwitch = false;   // 是否自动处理日数据
        if (!"-1".equals(rsjAutoTime)) {
            String[] rsjTime = rsjAutoTime.split(":");
            try {
                rsjHour = Integer.parseInt(rsjTime[0]);
                rsjMin = Integer.parseInt(rsjTime[1]);
                rsjSwitch = true;
            } catch (Exception e) {
                rsjSwitch = false;
            }
        } else {
            rsjSwitch = false;
        }

        int ysjDate = 22;
        int ysjHour = 8;
        int ysjMin = 0;
        String ysjAutoTime = (String) this.servletContext.getAttribute("ysjAutoProcessTime");
        String isYsjAdjust = (String) this.servletContext.getAttribute("isYsjAdjust");
        boolean ysjSwitch = false;   //是否处理月数据
        if (!"-1".equals(ysjAutoTime)) {
            String[] ysjTime = ysjAutoTime.split("[\\s:]");
            try {
                ysjDate = Integer.parseInt(ysjTime[0]);
                ysjHour = Integer.parseInt(ysjTime[1]);
                ysjMin = Integer.parseInt(ysjTime[2]);
                ysjSwitch = true;
            } catch (Exception e) {
            }
        }


        String rsjAutoRecallTime = (String) this.servletContext.getAttribute("rsjAutoRecallTime");   //日数据自动补采
        int rsjRecallHour = 3;
        int rsjRecallMin = 30;
        boolean rsjRecallSwitch = false;   // 是否自动处理补招日数据
        if (!"-1".equals(rsjAutoRecallTime)) {
            String[] rsjTime = rsjAutoRecallTime.split(":");
            try {
                rsjRecallHour = Integer.parseInt(rsjTime[0]);
                rsjRecallMin = Integer.parseInt(rsjTime[1]);
                rsjRecallSwitch = true;
            } catch (Exception e) {
            }
        }

        int ysjRecallDate = 21;   //自动补招月数据
        int ysjRecallHour = 7;
        int ysjRecallMin = 00;
        String ysjAutoRecallTime = (String) this.servletContext.getAttribute("ysjAutoRecallTime");
        boolean ysjRecallSwitch = false;   //是否处理月数据
        if (!"-1".equals(ysjAutoRecallTime)) {
            String[] ysjTime = ysjAutoRecallTime.split("[\\s:]");
            try {
                ysjRecallDate = Integer.parseInt(ysjTime[0]);
                ysjRecallHour = Integer.parseInt(ysjTime[1]);
                ysjRecallMin = Integer.parseInt(ysjTime[2]);
                ysjRecallSwitch = true;
            } catch (Exception e) {
            }
        }

        String rsjAutoUploadTime = (String) this.servletContext.getAttribute("rsjAutoUploadTime");   //日数据自动上传
        int rsjUploadHour = 3;
        int rsjUploadMin = 30;
        boolean rsjUploadSwitch = false;   // 是否自动处理上传日数据
        if (!"-1".equals(rsjAutoUploadTime)) {
            String[] rsjTime = rsjAutoUploadTime.split(":");
            try {
                rsjUploadHour = Integer.parseInt(rsjTime[0]);
                rsjUploadMin = Integer.parseInt(rsjTime[1]);
                rsjUploadSwitch = true;
            } catch (Exception e) {
            }
        }

        int ysjUploadDate = 21;   //自动上传月数据
        int ysjUploadHour = 7;
        int ysjUploadMin = 00;
        String ysjAutoUploadTime = (String) this.servletContext.getAttribute("ysjAutoUploadTime");
        boolean ysjUploadSwitch = false;
        if (!"-1".equals(ysjAutoUploadTime)) {
            String[] ysjTime = ysjAutoUploadTime.split("[\\s:]");
            try {
                ysjUploadDate = Integer.parseInt(ysjTime[0]);
                ysjUploadHour = Integer.parseInt(ysjTime[1]);
                ysjUploadMin = Integer.parseInt(ysjTime[2]);
                ysjRecallSwitch = true;
            } catch (Exception e) {
            }
        }

        //处理5分钟数据参数
        
        int m5Hour = 7;
        int m5Min = 30;
        boolean m5Switch = false;   // 是否自动处理5分钟数据
        if (!"-1".equals(data5mAutoGenTime)) {
            String[] m5Time = data5mAutoGenTime.split(":");
            try {
                m5Hour = Integer.parseInt(m5Time[0]);
                m5Min = Integer.parseInt(m5Time[1]);
                m5Switch = true;
            } catch (NumberFormatException e) {
                m5Switch = false;
            }
        } else {
            m5Switch = false;
        }
        
        while (!stop) {// 线程未中断执行循环  
            try {
                Thread.sleep(60 * 1000); //每隔2000ms执行一次
                System.out.println(".");
                Calendar now = Calendar.getInstance();
                int nowMonth = now.get(Calendar.MONTH) + 1;
                int nowDate = now.get(Calendar.DAY_OF_MONTH);
                int nowHour = now.get(Calendar.HOUR_OF_DAY);
                int nowMin = now.get(Calendar.MINUTE);

                Calendar yestoday = Calendar.getInstance();
                yestoday.add(Calendar.DAY_OF_MONTH, -1);

                int yestodayMonth = yestoday.get(Calendar.MONTH) + 1;
                int yestodayDate = yestoday.get(Calendar.DAY_OF_MONTH);
                int yestodayhour = yestoday.get(Calendar.HOUR_OF_DAY);
                int yestodaymin = now.get(Calendar.MINUTE);

                if (rsjRecallSwitch) {    //自动补招日数据（前一天日数据）
                    if (rsjRecallHour == nowHour && rsjRecallMin <= nowMin && rsjRecallFlag != nowDate) {
                        String date = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMMdd");
                        //logger.info("准备补招日数据");
                        List<Map<String, Object>> list = rsjService.findAllDataRecall(currentOrgCode,
                                date, date, "and pointId is null ", 0, 999999);

                        StringBuilder deviceIds = new StringBuilder();
                        StringBuilder dates = new StringBuilder();
                        for (Map<String, Object> map : list) {
                            deviceIds.append(map.get("deviceId")).append(",");
                            dates.append(map.get("date")).append(",");
                        }
                        if (deviceIds.length() > 0) {
                            deviceIds.deleteCharAt(deviceIds.length() - 1);
                            dates.deleteCharAt(dates.length() - 1);
                        }
                        boolean result = taskService.addBatch(deviceIds.toString(), 10, dates.toString());
                        //logger.info(date + "日数据补招处理完毕("+list.size()+")");
                        rsjRecallFlag = nowDate;
                    }

                    if (ysjRecallSwitch) {
                        if (ysjRecallDate == nowDate && ysjRecallHour == nowHour && ysjRecallMin <= nowMin && ysjRecallFlag != nowMonth) {
                            String ydate = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMM");
                            //logger.info("准备处理月数据补招");

                            List<Map<String, Object>> list = ysjService.findAllDataRecall(currentOrgCode, ydate, "and pointId is null", 0, 9999);
                            StringBuilder deviceIds = new StringBuilder();
                            StringBuilder dates = new StringBuilder();
                            for (Map<String, Object> map : list) {
                                deviceIds.append(map.get("deviceId")).append(",");
                                dates.append(ydate).append(",");
                            }
                            if (deviceIds.length() > 0) {
                                deviceIds.deleteCharAt(deviceIds.length() - 1);
                                dates.deleteCharAt(dates.length() - 1);
                            }
                            boolean result = taskService.addBatch(deviceIds.toString(), 20, dates.toString());

                            //logger.info(ydate + "月数据处理完毕("+list.size()+")");
                            ysjRecallFlag = nowMonth;
                        }
                    }
                }

                if (rsjSwitch) {    //自动处理日数据（前一天日数据）
                    if (rsjHour == nowHour && rsjMin <= nowMin && rsjFlag != nowDate) {
                        String date = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMMdd");
                        //logger.info("准备处理日数据");
                        rsjService.trCopyByOrg(currentOrgCode, date, -1, -1);//获取原始数据

                        if ("是".equals(isRsjAdjust) || "yes".equalsIgnoreCase(isRsjAdjust)) {
                            String condition = " and pointId is null";
                            boolean result = rsjService.trBatchCreate(currentOrgCode, date, condition, Double.parseDouble(rsjRateBase) / 100 - 0.05, "Lock"); //生产缺失数据
                            result = rsjService.updateAllByRateV2(currentOrgCode, date, "and pointId is not null", Double.parseDouble(rsjRateBase));
                        }
                        //logger.info(date + "日数据处理完毕");
                        rsjFlag = nowDate;
                    }
                }
                if (ysjSwitch) {
                    if (ysjDate == nowDate && ysjHour == nowHour && ysjMin <= nowMin && ysjFlag != nowMonth) {
                        String ydate = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMM");
                        //logger.info("准备处理月数据");
                        ysjService.trCopyByOrg(currentOrgCode, ydate, -1, -1);//获取原始数据
                        if ("是".equals(isYsjAdjust) || "yes".equalsIgnoreCase(isYsjAdjust)) {
                            String condition = " and pointId is null";
                            boolean result = ysjService.trBatchCreate(currentOrgCode, ydate, condition, Double.parseDouble(ysjRateBase) - 0.05, "Lock"); //生产缺失数据
                            result = ysjService.updateAllByRateV2(currentOrgCode, ydate, "and pointId is not null", Double.parseDouble(ysjRateBase));
                        }
                        
                        ysjService.adjustMMTime(Integer.parseInt(ydate.substring(0,4)),
                                Integer.parseInt(ydate.substring(4))                                
                                , startDay);
                        //logger.info(ydate + "月数据处理完毕");
                        ysjFlag = nowMonth;
                    }
                }

                if (rsjUploadSwitch) {    //自动上传日数据（前一天日数据）
                    if (rsjUploadHour == nowHour && rsjUploadMin <= nowMin && rsjUploadFlag != nowDate) {
                        String date = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMMdd");
                        //logger.info("准备处理上传日数据");
                        taskUploadService.add(-1, 200, date);
                        //logger.info(date + "日数据上传处理完毕");
                        rsjUploadFlag = nowDate;
                    }
                }
                if (ysjRecallSwitch) {
                    if (ysjUploadDate == nowDate && ysjUploadHour == nowHour && ysjUploadMin <= nowMin && ysjUploadFlag != nowMonth) {
                        String ydate = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMM");
                        //logger.info("准备处理上传月数据");
                        taskUploadService.add(-1, 300, ydate);
                        //logger.info(ydate + "月数据上传处理完毕");
                        ysjUploadFlag = nowMonth;
                    }
                }
                
                if (m5Switch) {    //自动处理5分钟数据（前一天日数据）(处理时间在同一小时内)
                    if (m5Hour == nowHour && m5Min <= nowMin && data5mFlag != nowDate) {
                        String date = DateUtil.get(new Date(yestoday.getTimeInMillis()), "yyyyMMdd");
                        //logger.info("准备处理日数据");
                        System.out.println("处理5分钟数据");
                        //temp5MService.trAddAllForTheDay(date, "01");
                        m5Service.trAddAllForTheDay(date, "01", 0.98);
                        System.out.println("5分钟处理完毕");
                        data5mFlag = nowDate;
                    }
                }
            } catch (InterruptedException e) {
                //System.out.print(this.getName());
                e.printStackTrace();
            } catch (Throwable t) {
                //System.out.print(this.getName());
                t.printStackTrace();
            }
        }
        //logger.info("结束执行线程***********");
        System.out.println("*****结束线程********");
    }
}
